from rest_framework import serializers, status
from rest_framework import exceptions

from prj001.models.cc import CC
from prj001.models.cure import Cure
from prj001.models.summary import Summary
from prj001.models.results import Results
from prj001.models.history import History
from prj001.models.relevant import Relevant

from django.db import transaction

from .create import update_model, computed_cure


def validate_person(value):
    person = value.get('person')
    if not person:
        raise serializers.ValidationError(
            detail='缺少person参数',
            code=status.HTTP_400_BAD_REQUEST)
    return value


def save_model_id(value, user=None, obj=None):
    try:
        obj_ = obj.objects.get(person_id=value)
    except obj.DoesNotExist:
        obj_ = None
        pass
    if obj_:
        obj_.owner = user
        obj_.save()


def synchronization_model(id_, user=None):

    save_model_id(id_, user, CC)
    save_model_id(id_, user, Cure)
    save_model_id(id_, user, Summary)
    save_model_id(id_, user, Results)
    save_model_id(id_, user, History)
    save_model_id(id_, user, Relevant)


def update_relevanted_tables(obj=None, request=None, checked_status='未审核', checked_reasons=None):
    with transaction.atomic(savepoint=True):
        point = transaction.savepoint()

        try:
            obj.is_checked = checked_status
            obj.reasons_for_not_passing = checked_reasons
            cure_degree = computed_cure(tps='object', _ID=obj.id)
            info_degree = update_model(obj, tps='info')
            obj.degree_of_completion = '%.2f%%' % ((cure_degree + info_degree) * 100)
            obj.save()
            # id_ = obj.id
            # # update all relevanted tables
            # synchronization_model(id_, user=request.user)
        except Exception:
            transaction.savepoint_rollback(point)
            return False
    return True


def validate_perm(req):
    '''check => user has all perm'''
    if not req.user.has_perm('prj001.prj001_all'):
        raise exceptions.PermissionDenied(detail={'msg': '对不起, 您没有权限进行审核'})
